package drongo.desktop.tools.events
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class TraceableEvent extends Event
	{
		/**
		 * 上一个动作 
		 */		
		public var last:TraceableEvent;
		/**
		 * 当前完成量 
		 */		
		public var index:Number;
		/**
		 * 总量 
		 */		
		public var total:Number;
		/**
		 * 动作名称 
		 */		
		public var actionName:String;
		/**
		 * 数据，如果有需要的话
		 */
		public var data:Object;
		
		public function TraceableEvent(type:String,actionName:String,data:Object=null,index:Number=0,total:Number=0, last:TraceableEvent=null,bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.actionName=actionName;
			this.data=data;
			this.index=index;
			this.total=total;
			this.last=last;
		}
		/**
		 * 获取第一个发起者 
		 * @return
		 */		
		public function get first():TraceableEvent{
			var action:TraceableEvent=this;
			var result:TraceableEvent;
			while(action){
				if(!action.last){
					result=action;
				}
				action=action.last;
			}
			return action;
		}
		public function destroy():void{
			this.actionName=null;
			this.data=null;
			this.index=NaN;
			this.total=NaN;
			if(last){
				last.destroy();
			}
			this.last=null;
		}
		override public function toString():String{
			 return _toString(0);
		}
		private function _toString(tabIndex:int):String{
			var str:String="";
			str+=getTab(tabIndex)+this.actionName+" "+this.data;
			if(this.type==PROGRESS){
				str+=" Progress:"+int(index/total*100)+"%";
			}
			if(last){
				str+="\n";
				str+=last._toString(tabIndex+1);
			}
			return str;
		}
		private function getTab(count:uint):String{
			var str:String="";
			for (var i:int = 0; i < count; i++) 
			{
				str+="	";
			}
			return str;
		}
		/**
		 * 完成事件 
		 */		
		public static const COMPLETE:String="complete";
		/**
		 * 进度事件 
		 */		
		public static const PROGRESS:String="progress";
		/**
		 * 错误事件 
		 */		
		public static const ERROR:String="error";
		/**
		 * 快速添加事件方法 
		 * @param target
		 * @param handler
		 */		
		public static function AddEvents(target:EventDispatcher,handler:Function):void{
			target.addEventListener(TraceableEvent.COMPLETE,handler);
			target.addEventListener(TraceableEvent.PROGRESS,handler);
			target.addEventListener(TraceableEvent.ERROR,handler);
		}
		/**
		 * 快速删除事件方法 
		 * @param target
		 * @param handler
		 * 
		 */		
		public static function RemoveEvents(target:EventDispatcher,handler:Function):void{
			target.removeEventListener(TraceableEvent.COMPLETE,handler);
			target.removeEventListener(TraceableEvent.PROGRESS,handler);
			target.removeEventListener(TraceableEvent.ERROR,handler);
		}
	}
}